package org.net5ijy.security.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.config.handler.CustomAuthenticationFailureHandler;
import org.net5ijy.security.config.security.SecurityConfig;
import org.net5ijy.security.util.RequestUtil;
import org.net5ijy.security.util.ResponseMessage;
import org.net5ijy.security.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * AdministratorController
 *
 * @author XGF
 * @date 2020/11/30 22:37
 */
@Controller
public class AdministratorController {

  @Autowired(required = false)
  PersistentTokenBasedRememberMeServices rememberMeServices;

  @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
  public String index() {
    return "redirect:/user/users";
  }

  @RequestMapping(value = "/login", method = {RequestMethod.GET})
  public String login(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    // 如果已经登录了，转到首页
    if (auth != null
        && !SecurityConfig.ANONYMOUS_USER.equalsIgnoreCase(auth.getName())) {
      return "redirect:/";
    }
    // 如果是AJAX请求，返回一个登录超时的JSON回去
    if (RequestUtil.isAjax(request)) {
      // content-type
      response.setContentType(ResponseUtil.APPLICATION_JSON_UTF8);
      // 设置响应码401
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      // 创建消息对象
      ResponseMessage msg = ResponseMessage.error();
      msg.addAttribute(ResponseMessage.EXCEPTION_ATTR_KEY, ResponseUtil.SESSION_TIMEOUT_MESSAGE);
      // 响应
      response.getWriter().print(SecurityConfig.toJson(msg));
      return null;
    }
    return "login";
  }

  @RequestMapping(value = "/login-error", method = {RequestMethod.GET})
  public ModelAndView loginError(HttpServletRequest request) {
    ModelAndView model = new ModelAndView("login");
    Exception ex = (Exception) request.getSession().getAttribute(
        CustomAuthenticationFailureHandler.SESSION_LOGIN_EXCEPTION_KEY);
    if (ex != null) {
      model.addObject("errorMsg", ex.getMessage());
      request.getSession()
          .removeAttribute(
              CustomAuthenticationFailureHandler.SESSION_LOGIN_EXCEPTION_KEY);
    } else {
      model.addObject("errorMsg", "登陆失败，账号或者密码错误！");
    }
    return model;
  }

  @RequestMapping(value = "/Access_Denied", method = {RequestMethod.GET, RequestMethod.POST})
  public String accessDeniedPage(ModelMap model) {
    Authentication auth = SecurityContextHolder.getContext()
        .getAuthentication();
    String name = auth.getName();
    model.addAttribute("loginUser", name);
    return "accessDenied";
  }

  @RequestMapping(value = "/error50x", method = {RequestMethod.GET, RequestMethod.POST})
  public ModelAndView error50x() {
    return new ModelAndView("error50x");
  }
}
